package com.aplink.generic.widgets.hacky;

import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import com.google.android.gms.maps.model.Marker;

public abstract class OnInfoWindowElemTouchListener implements OnTouchListener {
	private final Runnable confirmClickRunnable = new Runnable() {
		@Override
		public void run() {
			if (endPress()) {
				onClickConfirmed(view, marker);
			}
		}
	};
	private final Handler handler = new Handler();

	private Marker marker;
	private boolean pressed = false;

	private final View view;

	public OnInfoWindowElemTouchListener(View view) {
		this.view = view;
	}

	private boolean endPress() {
		if (pressed) {
			pressed = false;
			view.setPressed(false);
			handler.removeCallbacks(confirmClickRunnable);
			if (marker != null) {
				marker.hideInfoWindow();
			}
			return true;
		}
		return false;
	}

	public Marker getMarker() {
		return marker;
	}

	protected abstract void onClickConfirmed(View v, Marker marker);

	@Override
	public boolean onTouch(View vv, MotionEvent event) {
		if (0 <= event.getX() && event.getX() <= view.getWidth()
		        && 0 <= event.getY() && event.getY() <= view.getHeight()) {
			switch (event.getActionMasked()) {
				case MotionEvent.ACTION_DOWN:
					startPress();
					break;
				case MotionEvent.ACTION_UP:
					handler.postDelayed(confirmClickRunnable, 150);
					break;
				case MotionEvent.ACTION_CANCEL:
					endPress();
					break;
				default:
					break;
			}
		} else {
			endPress();
		}
		return false;
	}

	public void setMarker(Marker marker) {
		this.marker = marker;
	}

	private void startPress() {
		if (!pressed) {
			pressed = true;
			view.setPressed(true);
			handler.removeCallbacks(confirmClickRunnable);
			if (marker != null) {
				marker.showInfoWindow();
			}
		}
	}
}